package com.zzyl.nursing.service.impl;

import java.util.List;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.CodeGenerator;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.bean.BeanUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.*;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.concurrent.Executors;

/**
 * 入住管理Service业务层处理
 *
 * @author ruiyi
 * @date 2025-10-10
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper,CheckIn> implements ICheckInService
{
    @Autowired
    private CheckInMapper checkInMapper;
    @Autowired
    private ElderMapper elderMapper;
    @Autowired
    private CheckInConfigMapper checkInConfigMapper;
    @Autowired
    private ContractMapper contractMapper;
    @Autowired
    private BedMapper bedMapper;
    /**
     * 查询入住管理
     *
     * @param id 入住管理主键
     * @return 入住管理
     */
    @Override
    public CheckIn selectCheckInById(Long id)
    {
        return getById(id);
    }
    /**
     * 查询入住管理列表
     *
     * @param checkIn 入住管理
     * @return 入住管理
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn)
    {
        return checkInMapper.selectCheckInList(checkIn);
    }
    /**
     * 新增入住管理
     *
     * @param checkIn 入住管理
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn)
    {
        return save(checkIn)?1:0;
    }
    /**
     * 修改入住管理
     *
     * @param checkIn 入住管理
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn)
    {
        return updateById(checkIn)?1:0;
    }
    /**
     * 批量删除入住管理
     *
     * @param ids 需要删除的入住管理主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids))?1:0;
    }
    /**
     * 删除入住管理信息
     *
     * @param id 入住管理主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id)
    {
        return removeById(id)?1:0;
    }
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int apply(CheckInApplyDto dto) {
        CheckInConfigDto configDto = dto.getCheckInConfigDto();
        CheckInElderDto elderDto = dto.getCheckInElderDto();
        CheckInContractDto contractDto = dto.getCheckInContractDto();
        List<ElderFamilyDto> elderFamilyDtoList = dto.getElderFamilyDtoList();
        LambdaQueryWrapper<Elder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Elder::getIdCardNo,elderDto.getIdCardNo());
        queryWrapper.eq(Elder::getStatus,4);
        Elder elder = elderMapper.selectOne(queryWrapper);
        if(elder!=null){
            throw new BaseException("该老人已入住");
        }
//更新床位的状态
        Long bedId = configDto.getBedId();
        Bed bed = bedMapper.selectById(bedId);
        if(bed==null){
            throw new BaseException("请选择正确的床位");
        }
        bed.setBedStatus(1);
        bedMapper.updateById(bed);
        elder = saveOrUpdateElder(elderDto,bed);
        saveContract(contractDto,elder,configDto);
        CheckIn checkIn = saveCheckIn(elder,configDto,elderFamilyDtoList);
        saveCheckInConfig(contractDto,elder,configDto,checkIn);
        return 1;
    }

    private void saveCheckInConfig(CheckInContractDto contractDto, Elder elder, CheckInConfigDto configDto, CheckIn checkIn) {
        CheckInConfig checkInConfig = new CheckInConfig();
        checkInConfig.setCheckInId(checkIn.getId());
        checkInConfig.setNursingLevelId(configDto.getNursingLevelId());
        checkInConfig.setNursingLevelName(configDto.getNursingLevelName());
        checkInConfig.setFeeStartDate(configDto.getFeeStartDate());
        checkInConfig.setFeeEndDate(configDto.getFeeEndDate());
        checkInConfig.setDeposit(configDto.getDeposit());
        checkInConfig.setNursingFee(configDto.getNursingFee());
        checkInConfig.setBedFee(configDto.getBedFee());
        checkInConfig.setInsurancePayment(configDto.getInsurancePayment());
        checkInConfig.setGovernmentSubsidy(configDto.getGovernmentSubsidy());
        checkInConfig.setOtherFees(configDto.getOtherFees());
        checkInConfigMapper.insert(checkInConfig);
    }
    private CheckIn saveCheckIn(Elder elder, CheckInConfigDto configDto,List<ElderFamilyDto> elderFamilyDtoList) {
        CheckIn checkIn = new CheckIn();
        checkIn.setElderName(elder.getName());
        checkIn.setElderId(elder.getId());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setStartDate(configDto.getStartDate());
        checkIn.setEndDate(configDto.getEndDate());
        checkIn.setNursingLevelName(configDto.getNursingLevelName());
        checkIn.setBedNumber(elder.getBedNumber());
        checkIn.setStatus(0);  //(0: 已入住, 1: 已退住)
        // 把家属信息转成json字符串
        String jsonStr = JSONUtil.toJsonStr(elderFamilyDtoList);
        checkIn.setRemark(jsonStr);
        checkInMapper.insert(checkIn);
        return checkIn;
    }
    private void saveContract(CheckInContractDto contractDto,Elder elder,CheckInConfigDto configDto) {
        Contract contract = new Contract();
        contract.setElderId(elder.getId());
        contract.setContractName(contractDto.getContractName());
        contract.setContractNumber("HT"+CodeGenerator.generateContractNumber());
        contract.setAgreementPath(contractDto.getAgreementPath());
        contract.setThirdPartyPhone(contractDto.getThirdPartyPhone());
        contract.setThirdPartyName(contractDto.getThirdPartyName());
        contract.setElderName(elder.getName());
        contract.setStartDate(configDto.getStartDate());
        contract.setEndDate(configDto.getEndDate());
        contract.setStatus(1);  // 状态 (0: 未生效, 1: 已生效, 2: 已过期, 3: 已失效)
        contract.setSignDate(contractDto.getSignDate());
        contractMapper.insert(contract);
    }
    private Elder saveOrUpdateElder(CheckInElderDto elderDto,Bed bed) {
        LambdaQueryWrapper<Elder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Elder::getIdCardNo,elderDto.getIdCardNo());
        Elder elder = elderMapper.selectOne(queryWrapper);
        if(elder==null){
            elder = new Elder();
            elder.setName(elderDto.getName());
            elder.setImage(elderDto.getImage());
            elder.setIdCardNo(elderDto.getIdCardNo());
            elder.setSex(elderDto.getSex());
            elder.setStatus(4);   //状态（0：禁用，1:启用  2:请假 3:退住中 4入住中 5已退住）
            elder.setPhone(elderDto.getPhone());
            elder.setBirthday(elderDto.getBirthday());
            elder.setAddress(elderDto.getAddress());
            elder.setIdCardNationalEmblemImg(elderDto.getIdCardNationalEmblemImg());
            elder.setIdCardPortraitImg(elderDto.getIdCardPortraitImg());
            elder.setBedNumber(bed.getBedNumber());
            elder.setBedId(bed.getId());
            elderMapper.insert(elder);
        }else{
            elder.setName(elderDto.getName());
            elder.setImage(elderDto.getImage());
            elder.setIdCardNo(elderDto.getIdCardNo());
            elder.setSex(elderDto.getSex());
            elder.setStatus(4);   //状态（0：禁用，1:启用  2:请假 3:退住中 4入住中 5已退住）
            elder.setPhone(elderDto.getPhone());
            elder.setBirthday(elderDto.getBirthday());
            elder.setAddress(elderDto.getAddress());
            elder.setIdCardNationalEmblemImg(elderDto.getIdCardNationalEmblemImg());
            elder.setIdCardPortraitImg(elderDto.getIdCardPortraitImg());
            elder.setBedNumber(bed.getBedNumber());
            elder.setBedId(bed.getId());
            elderMapper.updateById(elder);
        }
        return elder;
    }
    /**
     * 第六天作业
     * @param checkInId
     * @return
     */
    @Override
    public CheckInDetailVo selectCheckInDetailById(Long checkInId) {
        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();
        // 1、查询checkIn
        CheckIn checkIn = getById(checkInId);
        Long elderId = checkIn.getElderId();
        // 查询老人信息
        LambdaQueryWrapper<Elder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Elder::getIdCardNo,checkIn.getIdCardNo());
        Elder elder = elderMapper.selectOne(queryWrapper);
        CheckInElderVo checkInElderVo = new CheckInElderVo();
        BeanUtils.copyProperties(elder,checkInElderVo);
        // 根据生日或者身份证号计算年龄
        int age = DateUtil.ageOfNow(elder.getBirthday());
        checkInElderVo.setAge(age);
        checkInDetailVo.setCheckInElderVo(checkInElderVo);
        LambdaQueryWrapper<Contract> queryWrapper2 = new LambdaQueryWrapper<>();
        queryWrapper2.eq(Contract::getElderId,elderId);
        Contract contract = contractMapper.selectOne(queryWrapper2);
        checkInDetailVo.setContract(contract);
        String remark = checkIn.getRemark();
        // 把json字符串转成List
        List<ElderFamilyVo> list = JSONUtil.toList(remark, ElderFamilyVo.class);
        checkInDetailVo.setElderFamilyVoList(list);
        LambdaQueryWrapper<CheckInConfig> queryWrapper3 = new LambdaQueryWrapper<>();
        queryWrapper3.eq(CheckInConfig::getCheckInId,checkIn.getId());
        CheckInConfig checkInConfig = checkInConfigMapper.selectOne(queryWrapper3);
        CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
        BeanUtils.copyProperties(checkInConfig,checkInConfigVo);
        checkInConfigVo.setStartDate(checkIn.getStartDate());
        checkInConfigVo.setEndDate(checkIn.getEndDate());
        checkInConfigVo.setBedNumber(checkIn.getBedNumber());
        checkInDetailVo.setCheckInConfigVo(checkInConfigVo);
        return checkInDetailVo;
    }
}
